/*
 * TaskQueue.cpp
 *
 *  Created on: 2012-12-28
 *      Author: yangentao@gmail.com
 */

#include "TaskQueue.h"

namespace ftp {
using namespace yet;

TaskQueue::TaskQueue() :
		Super() {
	taskOp = taskAND;
}
TaskQueue::TaskQueue(FtpContext* c, TaskOp taskOp ) :
		Super(c) {
	this->taskOp = taskOp;
}
TaskQueue::~TaskQueue() {

}
void TaskQueue::append(boost::shared_ptr<ITask> task){
	commands.push_back(task);
}
Task* TaskQueue::appendTask() {
	Task* t = new Task(context);
	boost::shared_ptr<ITask> cmd(t);
	commands.push_back(cmd);
	return t;
}
TaskQueue* TaskQueue::appendQueue() {
	TaskQueue* q = new TaskQueue(context);
	boost::shared_ptr<ITask> cmd(q);
	commands.push_back(cmd);
	return q;
}
bool TaskQueue::execute() {
	AutoLock alFail(failedCommands);
	failedCommands.clear();
	alFail.unLock();
	AutoLock al(commands);
	while (!commands.empty()) {
		boost::shared_ptr<ITask> cmd = commands.pop_front();
		if (cmd->execute()) {
			continue;
		} else {
			AutoLock al2(failedCommands);
			failedCommands.push_back(cmd);
			if ((taskOp == taskAND) || !context->sock.isValidSocket()) {
				while (!commands.empty()) {
					cmd = commands.pop_front();
					failedCommands.push_back(cmd);
				}
				return false;
			}
		}
	}
	return true;
}

} /* namespace yet */
